package com.chinasofti.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(value = "/login.jsp",dispatcherTypes={DispatcherType.REQUEST,DispatcherType.INCLUDE,DispatcherType.ERROR})
public class LoginCookieFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String username = null;
        String pwd = null;

        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie cookie:cookies){
                if(cookie.getName().equals("username")){
                    username = cookie.getValue();
                }
                if(cookie.getName().equals("pwd")){
                    pwd = cookie.getValue();
                }
            }
        }

            if(username == null && pwd == null){
                filterChain.doFilter(servletRequest,servletResponse);
            }else {
                request.getRequestDispatcher("login?username="+username+"&pwd="+pwd).forward(servletRequest,servletResponse);
            }

    }

    @Override
    public void destroy() {

    }
}
